/*
 * 太原科技大学。
 * Copyright 2021, YCHS Information&Science Technology Co.,Ltd,
 * All rights reserved.
 */
package com.itheima.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author liuchao
 * @version 1.0
 * @date 2024/3/21
 */

@Component
public class AliOSSUtils {
    //服务器域名
    @Autowired
    private AliOSSProperties aliOSSProperties;

    /**
     * 实现上传文件到oss
     */
    public String upload(MultipartFile file) throws IOException, ClientException {
        //获取参数
        String accessKeyId = aliOSSProperties.getAccessKeyId();
        String accessKeySecret = aliOSSProperties.getAccessKeySecret();
        String bucketName = aliOSSProperties.getBucketName();
        String endpoint = aliOSSProperties.getEndpoint();

        //获取服务器密钥，密钥在环境变量中配置了
        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
        InputStream inputStream=file.getInputStream();

        //避免文件覆盖，使用uuid和文件拓展名
        String originalFilename=file.getOriginalFilename();//获取返回文件流全名
        String uuidName= UUID.randomUUID().toString();//生成一个uuid唯一标识
        String endName=originalFilename.substring(originalFilename.lastIndexOf("."));//通过最后一个“.”获取
        String fileName=uuidName+endName;//最终拼接的文件名
        //上传到oss
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);

        // 创建PutObject请求,新版服务器必要
        PutObjectResult result = ossClient.putObject(putObjectRequest);

        //文件访问路径
        String url=endpoint.split("//")[0]+"//"+bucketName+"."+endpoint.split("//")[1]+"/"+fileName;
        //关闭oss
        ossClient.shutdown();
        return url;//返回对应url
    }

}
